//
//  MeatShopViewController.m
//  PigMarket
//
//  Created by 张敬 on 2019/7/19.
//  Copyright © 2019年 pigmarket.oc. All rights reserved.
//

#import "MeatShopViewController.h"
#import "MeatShopRightSideCell.h"
#import "MeatShopRightModel.h"
#import "MeatShopLeftSideCell.h"
#import "UITableView+FDTemplateLayoutCell.h"
#import "MeatShopBottomer.h"
#import "AddShoppingCartAnimationTool.h"
#import "MeatShopSectionModel.h"
#import "MeatShopCartBox.h"

#define leftCellIdentifier @"leftCellIdentifier"
#define rightCellIdentifier @"rightCellIdentifier"


@interface MeatShopViewController ()<UITableViewDataSource, UITableViewDelegate, MeatShopCellDelegate>

@property (nonatomic, strong) UITableView *leftTableView;
@property (nonatomic, strong) UITableView *rightTableView;

@property (nonatomic, strong) NSArray *leftArray;
@property (nonatomic, strong) NSMutableArray *aimsArr;

@property (nonatomic, strong) MeatShopBottomer *bottomer;
\
@property (nonatomic, assign) BOOL isShowBox;

@property (nonatomic, assign) NSInteger currentShopCartTotalNumbar;

@property (nonatomic) NSInteger currentLeftSideSectionValue; // 当前左边tableView选中的row值
@property (nonatomic) BOOL isInSelectedAnimationDuration;    // 是否正处于选中过程的动画当中

@end

@implementation MeatShopViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    [self setUpView];
}

- (void)setUpView {
    [self initView];
    [self initData];
}

- (void)initView{
    
    self.currentLeftSideSectionValue = 0;
    self.currentShopCartTotalNumbar = 0;
    self.isShowBox = YES;
    
    self.view.backgroundColor = mBackgroudColor;
    
    [self.view addSubview:self.leftTableView];
    [self.view addSubview:self.rightTableView];
    [self.view addSubview:self.bottomer];
    
    CGFloat h = KScreenHeight - (TJ_MeatShop_Header + _bottomer.height + 52);
    _rightTableView.height = _leftTableView.height = h;
    _rightTableView.height += 10;
    _bottomer.mj_y = self.leftTableView.bottom;
    
    [self.rightTableView addObserver:self
                          forKeyPath:@"contentOffset"
                             options:NSKeyValueObservingOptionNew
                             context:nil];
}

- (void)initData{
    
    _leftArray = [[NSArray alloc] initWithObjects:@"促销活动",@"臀尖肉",@"五花肉",@"坐臀肉",@"前腿肉",@"前排肉",@"奶脯肉",@"弹子肉", nil];

    NSData *jsonData = [NSData dataWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"newsData" ofType:@"json"]];
    
    
    @weakify(self);
    [_leftArray enumerateObjectsUsingBlock:^(id  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
        @strongify(self);
        
        MeatShopSectionModel *model = [[MeatShopSectionModel alloc] init];
        model.name = (NSString *) obj;
        model.section = idx;
        
        NSMutableArray *aims = [NSMutableArray array];
        for (NSInteger i = 0; i<= idx; i++) {
            
            NSArray *rightArray = [NSArray yy_modelArrayWithClass:[MeatShopRightModel class] json:jsonData];
            
            MeatShopRightModel *cellModel = [[MeatShopRightModel alloc] init];
            cellModel = rightArray[i];
            [aims addObject:cellModel];
        }
        
        model.rows = aims;
        [self.aimsArr addObject:model];
    }];
}

#pragma mark - ScrollViewDelegate

- (void)scrollViewDidScroll:(UIScrollView *)scrollView {
    
    if ([scrollView isEqual:self.rightTableView] && self.isInSelectedAnimationDuration == NO) {
        
        NSInteger section = [self.rightTableView indexPathForCell:self.rightTableView.visibleCells.firstObject].section;
        if (self.currentLeftSideSectionValue != section) {
            
            self.currentLeftSideSectionValue = section;
            NSInteger newSelectedIndex = section;
            
            [self.leftTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:newSelectedIndex inSection:0]
                                      atScrollPosition:UITableViewScrollPositionMiddle
                                              animated:YES];
            [self.leftTableView reloadData];
        }
    }
}

- (void)scrollViewDidEndDecelerating:(UIScrollView *)scrollView {
    
    if ([scrollView isEqual:self.rightTableView]) {
       self.isInSelectedAnimationDuration = NO;
    }
}


- (void)scrollViewDidEndScrollingAnimation:(UIScrollView *)scrollView {
    
    if ([scrollView isEqual:self.rightTableView]) {
        self.isInSelectedAnimationDuration = NO;
    }
}

#pragma mark - 折叠按钮点击代理

- (void)clickFoldLabel:(MeatShopRightSideCell *)cell{
    
    NSIndexPath *indexPath = [self.rightTableView indexPathForCell:cell];
    
    MeatShopSectionModel *sectionModel = self.aimsArr[indexPath.section];
    MeatShopRightModel *model = sectionModel.rows[indexPath.row];
    
    model.isOpening = !model.isOpening;
    [self.rightTableView beginUpdates];
    [self.rightTableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationFade];
    [self.rightTableView endUpdates];
}

//设置cell高度
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    if (tableView == self.leftTableView) {
        return 46;
    }
    
    MeatShopSectionModel *sectionModel = self.aimsArr[indexPath.section];
    if (sectionModel.rows.count > 0)
    {
        MeatShopRightModel *model = [sectionModel.rows objectAtIndex:indexPath.row];
        if (model.isOpening) {
            // 使用不缓存的方式
            return [self.rightTableView fd_heightForCellWithIdentifier:rightCellIdentifier configuration:^(id cell) {

                [self handleCellHeightWithNewsCell:cell indexPath:indexPath];
            }];
        }else{
            // 使用缓存的方式
            return [self.rightTableView fd_heightForCellWithIdentifier:rightCellIdentifier cacheByIndexPath:indexPath configuration:^(id cell) {

                [self handleCellHeightWithNewsCell:cell indexPath:indexPath];
            }];
        }
    } else{

        return 10;
    }
}

// 处理折叠cell高度
-(void)handleCellHeightWithNewsCell:(id)cell indexPath:(NSIndexPath *)indexPath{
    
    MeatShopRightSideCell *newsCell = (MeatShopRightSideCell *)cell;
    MeatShopSectionModel *sectionModel = self.aimsArr[indexPath.section];
    newsCell.newsModel = sectionModel.rows[indexPath.row];
}


#pragma mark - UITableView.delegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    
    if (tableView == self.leftTableView) {
        return self.aimsArr.count;
    }
    
    MeatShopSectionModel *model = self.aimsArr[section];
     return model.rows.count;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    
    if (tableView == self.leftTableView) {
        return 1;
    }
    
    return self.aimsArr.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // 左边的cell
    if (tableView == self.leftTableView) {
        MeatShopLeftSideCell *cell = [tableView dequeueReusableCellWithIdentifier:leftCellIdentifier forIndexPath:indexPath];
        cell.pigPartsLab.text = self.leftArray[indexPath.row];
        
        if (self.currentLeftSideSectionValue == indexPath.row) {
            [cell updateToSelectedStateAnimated:YES];
        }else{
            [cell updateToNormalStateAnimated:YES];
        }
        
        return cell ;
    } else {
        
        MeatShopRightSideCell *newsCell = [tableView dequeueReusableCellWithIdentifier:rightCellIdentifier];
        newsCell.cellDelegate = self;
        
        MeatShopSectionModel *sectionModel = self.aimsArr[indexPath.section];
        MeatShopRightModel *model = sectionModel.rows[indexPath.row];
        newsCell.newsModel = model;
        
        @weakify(self);
        newsCell.shopCartBlock = ^(UIButton *btn) {
            
            @strongify(self);
            
            model.isChicked = YES;
            
            self.currentLeftSideSectionValue = indexPath.section;
            self.currentShopCartTotalNumbar++;
            sectionModel.totalNumber++;
            
            UIImageView *image = [[UIImageView alloc] init];
            image.frame = CGRectMake(0, 0, 35, 35);
            image.image = [UIImage imageNamed:@"p1"];


            NSIndexPath *path = [NSIndexPath indexPathForRow:self.currentLeftSideSectionValue inSection:0];
            MeatShopLeftSideCell *cell =  (MeatShopLeftSideCell *)[self.leftTableView cellForRowAtIndexPath:path];

            [[AddShoppingCartAnimationTool shareTool] startAnimationandFromView:btn toView:self.bottomer.cartIcon imgView:image];

            if (self.currentShopCartTotalNumbar>0) {

                self.bottomer.cartTipNumberLab.hidden = NO;
                self.bottomer.cartTipNumberLab.text = [NSString stringWithFormat:@"%ld", (long)self.currentShopCartTotalNumbar];
            }
            
            if (sectionModel.totalNumber>0) {
                cell.shopCartTipNumber.hidden = NO;
                cell.shopCartTipNumber.text = [NSString stringWithFormat:@"%ld", (long)sectionModel.totalNumber];
            }
            
            [self.rightTableView reloadData];
        };

        return newsCell;
    }
    return [UITableViewCell new];
}


- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{

    if (tableView == self.rightTableView && section <_leftArray.count) {

        UIView *view = [UIView new];
        view.frame = CGRectMake(0, 0, KScreenWidth, 30);
        view.backgroundColor = mBackgroudColor;

        UILabel * label = [UILabel new];
        label.textColor = UIColorFromRGB(0x262626);
        label.font = mMediumFont(16);
        label.frame = CGRectMake(15, 0, KScreenWidth - 10, 30);

        MeatShopSectionModel *model = self.aimsArr[section];
        label.text = model.name;

        [view addSubview:label];
        return view;
    }
    return nil;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    return [tableView isEqual:self.rightTableView]?30 :0.01;
}


#pragma mark  - 点击 cell 的代理方法

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    
    // 右边tableView正在滑动而此时正在点击左边tableView的cell
    if ([tableView isEqual:self.leftTableView] && self.rightTableView.isDecelerating && self.rightTableView.isDragging) {
        
        [self.rightTableView setContentOffset:self.rightTableView.contentOffset animated:NO];
        [self.leftTableView setContentOffset:self.leftTableView.contentOffset animated:NO];
        return;
    }
    
    if ([tableView isEqual:self.leftTableView]) {
        
        NSInteger oldSelectedIndex = self.currentLeftSideSectionValue;
        NSInteger newSelectedIndex = indexPath.row;
        self.currentLeftSideSectionValue = newSelectedIndex;
        
        [self.leftTableView reloadData];
        
        // 重复点击同一个cell无效
        if (oldSelectedIndex == newSelectedIndex) {
            return;
        }
        
        self.isInSelectedAnimationDuration = YES;
        [self.rightTableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:newSelectedIndex]
                                   atScrollPosition:UITableViewScrollPositionTop animated:YES];
        
        // 解决最后两个cell点击不移动时出现的bug
        [self performSelector:@selector(makeIsInSelectedAnimationDurationEquilNO) withObject:nil afterDelay:0.05f];
        
    } else {
        
    }
}

#pragma mark - setter and  getter
//- 左边的 tableView
- (UITableView *)leftTableView {
    
    if (!_leftTableView) {
        
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 10, TJ_MeatShop_LeftSideWidth, 0)];
        [self.view addSubview:tableView];
        tableView.dataSource = self;
        tableView.delegate = self;
        tableView.backgroundColor = mBackgroudColor;
        tableView.separatorColor = KClearColor;
        [tableView registerClass:[MeatShopLeftSideCell class] forCellReuseIdentifier:leftCellIdentifier];
        if (@available(iOS 11.0, *)) {
            tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
        _leftTableView = tableView;
    }
    return _leftTableView;
}

// - 右边的 tableView
- (UITableView *)rightTableView {
    
    if (!_rightTableView) {
        
        UITableView *tableView = [[UITableView alloc] initWithFrame:CGRectMake(TJ_MeatShop_LeftSideWidth, 10, TJ_MeatShop_RightSideWidth, 0)];
        [self.view addSubview:tableView];
        tableView.dataSource = self;
        tableView.delegate = self;
        [tableView registerClass:[MeatShopRightSideCell class] forCellReuseIdentifier:rightCellIdentifier];
        tableView.backgroundColor = KWhiteColor;
        tableView.estimatedRowHeight = 0;
        tableView.estimatedSectionFooterHeight = 0;
        tableView.estimatedSectionHeaderHeight = 0;
        _rightTableView = tableView;
        if (@available(iOS 11.0, *)) {
            tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
        }
    }
    return _rightTableView;
}

- (MeatShopBottomer *)bottomer
{
    if (!_bottomer) {
        _bottomer = [[MeatShopBottomer alloc] init];
        
        @weakify(self);
        _bottomer.dealShowCartBlock = ^{
            @strongify(self);
            
            if (self.isShowBox) {
              
                self.isShowBox = NO;
                MeatShopCartBox *box = [[MeatShopCartBox alloc] init];
                [box showView];
                
//                box.dismissBlock = ^{
//                    self.isShowBox = YES;
//                };
            }
        };
    }
    return _bottomer;
}

- (NSMutableArray *)aimsArr{
    if (!_aimsArr) {
        _aimsArr = [NSMutableArray array];
    }
    return _aimsArr;
}

#pragma mark - Other

- (void)makeIsInSelectedAnimationDurationEquilNO {

    self.isInSelectedAnimationDuration = NO;
}

#pragma mark - System

- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary<NSKeyValueChangeKey,id> *)change context:(void *)context {
    
    // 点击左侧tableView中的cell触发移动
    if (self.isInSelectedAnimationDuration == YES) {
        [NSObject cancelPreviousPerformRequestsWithTarget:self selector:@selector(makeIsInSelectedAnimationDurationEquilNO) object:nil];
    }
}

- (void)dealloc {
    
    [self.rightTableView removeObserver:self forKeyPath:@"contentOffset"];
}

@end
